package com.topvision.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion;
import com.topvision.annotation.IgnoreAuth;
import com.topvision.controller.hes.LoginDTO;
import com.topvision.model.hes.HesExpert;
import com.topvision.model.hes.HesUserDeviceZwannumber;
import com.topvision.model.zwan.Userinfo;
import com.topvision.service.api.TokenApiService;
import com.topvision.service.api.hes.HesUserDeviceZwannumberService;
import com.topvision.service.api.user.UserService;
import com.topvision.model.api.TokenApi;
import com.topvision.model.hes.HesUser;
import com.topvision.service.hes.HesExpertService;
import com.topvision.uitl.redis.RedisBizUtilApi;
import com.topvision.uitl.redis.TokenUtil;
import com.topvision.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;


/**
 * 用户登陆
 * <p>
 * SWM 2017.05.13
 */
@RestController
@Api(value = "登录授权API", description = "用户登录获取token")
public class LoginController {

    Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private UserService userService;
    @Autowired
    private TokenApiService tokenApiService;
    @Autowired
    private RedisBizUtilApi redisBizUtilApi;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private HesUserDeviceZwannumberService hesUserDeviceZwannumberService;
    @Autowired
    private HesExpertService hesExpertService;

    /**
     * 用户登陆操作
     *
     * @param request
     * @return TokenApi 只返回必要字段，不得返回用户密码和敏感信息
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation(value = "登录帐号", produces = MediaType.APPLICATION_JSON_VALUE, notes = "登录系统", response = R.class)
    public R userlogin(HttpServletRequest request, @RequestBody LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        String mac = loginDTO.getMac();
        try {
            if (username != null) {
                //设置用户操作日志对象
                //根据jobnumber查询用户
                HesUser user = userService.getUserByUserName(username);
                if (user == null) {
                    return R.error("该用户暂未注册");
                }
                if (!StringUtils.isEmpty(password)) {
                    //验证密码（登陆操作）
                    String pass = Md5Util.getMd5("MD5", 0, null, password).toUpperCase();
                    user = userService.Login(username, pass);
                    if (user == null) {
                        return R.error("账号或密码错误");
                    }/* else {
                        if (0 == user.getStatus()) {
                            return R.error("您的账号还没有被激活");
                        }
                        if (-2 == user.getStatus()) {
                            return R.error("该人员已经离职");
                        }
                    }*/
                    //生成token
                    TokenApi tokenApiLast = tokenApiService.queryByJobNumber(user.getUsername());
                    TokenApi tokenApiNew = tokenUtil.createToken(tokenApiLast, user);

                    //获取用户ip,url.参数
                  /*  IPUtils iputil = new IPUtils();
                    logInfo.setIp(iputil.getIpAddr(request));
                    logInfo.setUrl(request.getRequestURL().toString());
                    logInfo.setParameter(HttpContextUtils.getParameterForLog(request));
                    logInfo.setEndTime(new Date());
                    sysoperationLogService.SaveLog(logInfo);
                    log.info("登陆日志：" + "门店号＝" + user.getStoreNumber() + "工号＝" + user.getJobNumber() + "姓名＝"
                            + user.getName() + "token＝" + tokenApiNew.getToken());*/
                    String result = getZwannumber(mac);
                    if (result != null) {
                        JSONObject json = JSON.parseObject(result);
                        Map<String, Object> map = new HashMap<>();
                        map.put("deviceid", mac);
                        List<HesUserDeviceZwannumber> hesUserDeviceZwannumberList = hesUserDeviceZwannumberService.queryByParam(map);
                        map.remove("deviceid");
                        map.put("username", username);
                        List<HesUserDeviceZwannumber> hesUserDeviceZwannumberListByName = hesUserDeviceZwannumberService.queryByParam(map);
                        HesUserDeviceZwannumber hesUserDeviceZwannumberByName = new HesUserDeviceZwannumber();
                        if (hesUserDeviceZwannumberListByName != null && hesUserDeviceZwannumberListByName.size() > 0) {
                            hesUserDeviceZwannumberByName = hesUserDeviceZwannumberListByName.get(0);
                        }
                        if (hesUserDeviceZwannumberList != null && hesUserDeviceZwannumberList.size() > 0) {
                            HesUserDeviceZwannumber hesUserDeviceZwannumberexist = hesUserDeviceZwannumberList.get(0);
                            String name = hesUserDeviceZwannumberexist.getUsername();
                            hesUserDeviceZwannumberexist.setUsername(username);
                            hesUserDeviceZwannumberexist.setZwannumber(json.getString("account"));
                            hesUserDeviceZwannumberexist.setPassword(json.getString("password"));

                            //若之前存在用过别的设备则删除
                            if (hesUserDeviceZwannumberByName != null && hesUserDeviceZwannumberByName.getDeviceid() != null) {
                                if (!hesUserDeviceZwannumberByName.getDeviceid().equals(mac)) {
                                    hesUserDeviceZwannumberService.delete(hesUserDeviceZwannumberByName.getId());
                                }
                            }
                            hesUserDeviceZwannumberService.update(hesUserDeviceZwannumberexist);
                            return R.success(tokenApiNew).put("user", user).put("zwan", json);
                        } else {
                            HesUserDeviceZwannumber hesUserDeviceZwannumber = new HesUserDeviceZwannumber();

                            if (hesUserDeviceZwannumberByName != null && hesUserDeviceZwannumberByName.getDeviceid() != null) {
                                hesUserDeviceZwannumberByName.setDeviceid(mac);
                                hesUserDeviceZwannumberByName.setUsername(username);
                                hesUserDeviceZwannumberByName.setZwannumber(json.getString("account"));
                                hesUserDeviceZwannumberByName.setPassword(json.getString("password"));
                                hesUserDeviceZwannumberService.updateByUserName(hesUserDeviceZwannumberByName);
                            }else{
                                hesUserDeviceZwannumberByName.setDeviceid(mac);
                                hesUserDeviceZwannumberByName.setUsername(username);
                                hesUserDeviceZwannumberByName.setZwannumber(json.getString("account"));
                                hesUserDeviceZwannumberByName.setPassword(json.getString("password"));
                                hesUserDeviceZwannumberService.save(hesUserDeviceZwannumberByName);
                            }

                            return R.success(tokenApiNew).put("user", user).put("zwan", json);
                        }

                    } else {
                        return R.success(tokenApiNew).put("user", user).put("zwan", "紫万帐号网络出错");
                    }

                    // return R.success(tokenApiNew);
                } else {
                    return R.error("密码为空");
                }
            } else {
                return R.error("username为空");
            }
        } catch (Exception e) {
            log.error("登陆异常", e);
            return R.error("登录错误");
        }
    }

    @IgnoreAuth
    @RequestMapping(value = "/expertlogin", method = RequestMethod.POST)
    @ApiOperation(value = "专家登录帐号", produces = MediaType.APPLICATION_JSON_VALUE, notes = "专家登录系统", response = R.class)
    public R expertlogin(HttpServletRequest request, @RequestParam String password, @RequestParam String username) {
        try {
            if (username != null) {
                //设置用户操作日志对象
                //根据jobnumber查询用户
                Map<String, Object> map = new HashMap<>();
                map.put("username", username);
                List<HesExpert> hesExperts = hesExpertService.queryByParam(map);
                HesExpert hesExpert = null;
                if (hesExperts != null) {
                    hesExpert = hesExperts.get(0);
                }
                if (hesExpert == null) {
                    return R.error("该用户暂未注册");
                }
                if (!StringUtils.isEmpty(password)) {
                    //验证密码（登陆操作）
                    String pass = Md5Util.getMd5("MD5", 0, null, password).toUpperCase();
                    hesExpert = hesExpertService.Login(username, pass);
                    if (hesExpert == null) {
                        return R.error("账号或密码错误");
                    }/* else {
                        if (0 == user.getStatus()) {
                            return R.error("您的账号还没有被激活");
                        }
                        if (-2 == user.getStatus()) {
                            return R.error("该人员已经离职");
                        }
                    }*/
                    //生成token
                    TokenApi tokenApiLast = tokenApiService.queryByJobNumber(hesExpert.getUsername());
                    HesUser user = new HesUser();
                    user.setUsername(hesExpert.getUsername());
                    TokenApi tokenApiNew = tokenUtil.createToken(tokenApiLast, user);

                    //获取用户ip,url.参数
                  /*  IPUtils iputil = new IPUtils();
                    logInfo.setIp(iputil.getIpAddr(request));
                    logInfo.setUrl(request.getRequestURL().toString());
                    logInfo.setParameter(HttpContextUtils.getParameterForLog(request));
                    logInfo.setEndTime(new Date());
                    sysoperationLogService.SaveLog(logInfo);
                    log.info("登陆日志：" + "门店号＝" + user.getStoreNumber() + "工号＝" + user.getJobNumber() + "姓名＝"
                            + user.getName() + "token＝" + tokenApiNew.getToken());*/


                    return R.success(tokenApiNew).put("expert", hesExpert);
                } else {
                    return R.error("密码为空");
                }
            } else {
                return R.error("username为空");
            }
        } catch (Exception e) {
            log.error("登陆异常", e);
            return R.error("登录错误");
        }
    }

    /**
     * 用户登出
     *
     * @param request
     */
    @RequestMapping(value = "/loginout", method = RequestMethod.POST)
    @ApiOperation(value = "退出当前帐号", produces = MediaType.APPLICATION_JSON_VALUE, notes = "推出系统，需带有token", response = R.class)
    public void loginout(HttpServletRequest request, String token) {
        //先从header里面找，在找request，最后参数
        if (StringUtils.isEmpty(token)) {
            // 从header中获取token

            token = request.getHeader("token");
            if (StringUtils.isEmpty(token)) {
                // 从参数中获取token
                token = request.getParameter("token");
            }
        }
        if (!StringUtils.isEmpty(token)) {
            // 删除用token信息
            //    redisBizUtilApi.removeApiToken(token);
            //      tokenApiService.deleteByToken(token);
        }
    }


    /**
     * 测试登陆产生token信息
     * http://localhost:8080/login
     *
     * @return
     */
    @RequestMapping(value = "/loginTest", method = RequestMethod.POST)
    @ApiOperation(value = "退出当前帐号", produces = MediaType.APPLICATION_JSON_VALUE, notes = "推出系统，需带有token", response = R.class)
    public R loginTest(@RequestBody LoginDTO loginDTO) {
        HesUser user = new HesUser();
        user.setUsername("topvision");
        System.out.print(loginDTO.getUsername());

        return R.success();
    }


    /**
     * 测试登陆产生token信息
     * http://localhost:8080/login
     *
     * @return
     */
    @RequestMapping(value = "/example", method = RequestMethod.POST)
    @ApiOperation(value = "DEMO请求", produces = MediaType.APPLICATION_JSON_VALUE, notes = "请求示例", response = R.class)
    public R helloworld() {
        return R.success("HELLO WORLD!!!!");
    }


    /**
     * token测试
     *
     * @param request
     */
    @IgnoreAuth
    @RequestMapping(value = "tokenTest", method = RequestMethod.GET)
    public R tokenTest(HttpServletRequest request) {
        HesUser user = new HesUser();
       /* user.setJobNumber("CS123456");
        user.setName("测试");
        user.setRoleId(1);*/
        //生成token
        TokenApi tokenApiNew = tokenUtil.createToken(null, user);
        return R.success(tokenApiNew);
    }

    //请求紫万获取帐号密码
    public static String getZwannumber(String mac) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("companyid", "101");
        map.put("mac", mac);//本处获取的是蓝牙的mac地址
        StringBuffer sb = new StringBuffer();
        sb.append("companyid=").append("101").append("&mac=").append(map.get("mac"));
        sb = new StringBuffer(Md5Util.getMd5("MD5", 0, null, sb.toString()));
        sb.append("123456");
        map.put("digest", Md5Util.getMd5("MD5", 0, null, sb.toString()));

        String result = HttpClientUtil.getZwanPostResult(Const.ZWAN_URL + "zwgw/getaccountfrommac", map);
        return result;
    }

}
